<template>
  <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="isshowdisable">
    <el-timeline>
      <el-timeline-item v-for="(item, index) in milepostList" :key="index + 'competitor'" color="#0A6ED2" style="margin-bottom: 20px;">
        {{ '里程碑' + (index + 1) }}
        <el-row>
          <el-col :span="12">
            <el-form-item :label="'里程碑名称'" :rules="rules.validateRequire">
              <el-input v-model="item.milepostname" :disabled="item.enabled === 1 || item.templatetype === '1' || item.milepoststate === 1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划达成日期" :rules="rules.validateRequire">
              <el-date-picker v-model="item.planfinishtime" type="date" @change="selectTime(index, item.planfinishtime)" placeholder="例：2021-01-01" value-format="yyyy-MM-dd" :disabled="item.enabled === 1 || item.milepoststate === 1"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任人" :rules="rules.validateRequire">
              <tl-sd-project-stakeholder-ref :initDisplayData.sync="item.responsible" :externalSelectedRowKeys="item.responsiblecode" @confirm="addConfirm(index, arguments)" title="责任人" :externalQueryParam="externalQueryParam" :isSingleSelect="true" :disabled="item.enabled === 1 || item.milepoststate === 1 || isshowdisable"></tl-sd-project-stakeholder-ref>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交付成果" :rules="rules.validateRequire">
              <el-input v-model="item.deliverable" :disabled="item.enabled === 1 || item.milepoststate === 1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <tl-index-Task style="margin-left: 120px;" :disabled="isshowdisable" :index="index" ref="task" :milepost="item" :milepostname="item.milepostname" :milepostcode="item.operatecode" :projectinfo="projectinfo" :planstate="planstate"></tl-index-Task>
        <el-col :span="8">
          <el-button type="text" v-if="(item.enableDelete || item.newadd !== 0) && !isshowdisable" style="margin-left:140px" @click="removeCompetitor(item, index)">删除里程碑</el-button>
        </el-col>
      </el-timeline-item>
    </el-timeline>
    <el-row v-if="!isshowdisable">
      <el-col :span="8">
        <el-button type="text" @click="addCompetitor" icon="el-icon-circle-plus-outline" style="margin-left:140px">新增里程碑</el-button>
        <el-button class="filter-item" type="text" icon="el-icon-circle-plus-outline" @click="openAddDialog('editTemplateForm')">按模板新增</el-button>
        <!-- <el-button class="filter-item" type="text" icon="el-icon-circle-plus-outline" :projectinfo="projectinfo" @click="openAddDialog('editProjectForm')">按项目新增</el-button> -->
      </el-col>
    </el-row>
    <!-- <tlsd-project-stakeholde-ref ref="sdProjectTeamRef" @confirm="getSdProjectTeamData" :externalQueryParam="externalQueryParamForPool"></tlsd-project-stakeholde-ref> -->
    <tlsd-project-team-ref ref="sdProjectTeamRef" @confirm="getSdProjectTeamData" :externalQueryParam="externalQueryParamForPool"></tlsd-project-team-ref>
    <tl-edit-template ref="editTemplateForm" @refresh="doRefresh" :parentId="parentId" :projectinfo="projectinfo" :isSingleSelect="false"></tl-edit-template>
    <tl-edit-project ref="editProjectForm" @refresh="doRefresh" :parentId="parentId" :projectinfo="projectinfo"></tl-edit-project>
  </el-form>
</template>

<script>
/** mixins */
import { mixin_edit } from "@tapui/mixins/mixin_edit"

/** 子组件 */
import TlSdProjectStakeholderRef from "../gpmProjectStakeholder/refList"
import tlsdProjectTeamRef from "@/views/gpm/gpmProjectTeam/refList"
import tlIndexTask from "./indexTask"
import tlEditTemplate from "./editTemplate"
import tlEditProject from "./editProject"
import { formatDate } from '@tapui/utils/date'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from "@tapui/utils/http"
/** VUE配置 */
export default {
  mixins: [mixin_edit],
  components: { tlsdProjectTeamRef, tlIndexTask, tlEditTemplate, tlEditProject, TlSdProjectStakeholderRef },
  data() {
    return {
      moduleTitle: "项目策划-里程碑",
      urlPrefix: "/sd/projectMilepost/",
      externalQueryParamForPool: {},
      url: {
        // 额外的url
        milepostLoadInfo: "/sd/projectMilepost/milepostLoadInfo",
        updateInfo: "/sd/projectMilepost/updateInfo",
        saveMilepost: "/sd/projectMilepost/saveMilepost",
        updateMilepostBatch: "/sd/projectMilepost/updateMilepostBatch"
      },
      milepostList: [],
      milepostIndex: -1,
      // 人员组件查询参数
      externalQueryParam: {
        qry_projectcode: this.projectinfo.projectcode // 项目编号
      }
    }
  },
  props: {
    parentId: {
      type: [Number, String],
      default: ""
    },
    operatecode: {
      type: String
    },
    projectinfo: {},
    planstate: {
      type: [Number, String],
      default: ""
    },
    isshowdisable: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    updatemilepostBatch() {
      postAction(this.url.updateMilepostBatch, { milepostList: this.milepostList }).then(res => {
        if (res.success) {
        } else {
          this.$tap.alert(res.message, "warning")
        }
      })
    },
    // 人员选择后赋值
    addConfirm(index, ...values) {
      this.$set(this.milepostList[index], "responsiblecode", values[0][1])
      this.$set(this.milepostList[index], "responsible", values[0][2])
      this.$set(this.milepostList[index], "projectcode", this.projectinfo.projectcode)
    },
    updateInfo() {
      return new Promise((resolve, reject) => {
          postAction(this.url.updateInfo, { milepostList: this.milepostList, projectcode: this.projectinfo.projectcode, planid: this.parentId }).then(res => {
            if (res.success) {
              resolve()
              // this.$refs.line.milepostLoadInfo()
            } else {
              this.$tap.alert(res.message, "warning")
              reject()
            }
          })
          })
    },
    selectTime(index, time) {
      if (new Date(time) > new Date(this.projectinfo.planenddate)) {
        this.$tap.alert("里程碑的计划达成时间不能晚于所属项目的计划结束时间！")
        this.milepostList[index].planfinishtime = ""
      }
      if (new Date(time) < new Date(this.projectinfo.planstartdate)) {
        this.$tap.alert("里程碑的计划达成时间不能早于所属项目的计划开始时间！")
        this.milepostList[index].planfinishtime = ""
      }
      let taskplanenddate = this.$refs.task[index].datas.filter((item) => {
        return item.planenddate !== null && item.planenddate !== undefined
      })
      taskplanenddate.forEach((item) => {
        if (this.formatDateToMicro(time) < this.formatDateToMicro(item.planenddate)) {
          this.$tap.alert('里程碑及任务的计划达成时间不能早于任务的计划达成时间！')
          this.milepostList[index].planfinishtime = null
          return
        }
      })
      //  if (new Date(time) < new Date()) {
      //     this.$tap.alert('里程碑的计划达成时间不能早于当前时间！')
      //     this.milepostList[index].planfinishtime = ''
      //   }
    },
    /** 打开新增对话框实现 */
    openAddDialog(editForm, rowData) {
      this.$refs[editForm].isAdd = true
      this.$refs[editForm].visible = true
      this.$refs[editForm].disableEditSubmit = false
      this.$refs[editForm].addFromPlan = true
    },
    removeCompetitor(item, index) {
      const that = this
      this.$tap
        .confirm("确定删除里程碑吗？")
        .then(_ => {
          // 不要了
          // if (item.templatetype === undefined || item.templatetype !== "1") {
          //   if (this.$refs.task[index].datas.length > 0) {
          //     this.$tap.alert("已关联任务，不允许删除！")
          //     return
          //   }
          // }
          deleteAction("/sd/projectMilepost/delete", { ids: item.id }).then(res => {
            if (res.success) {
              this.$tap.message(res.message, "success")
              this.$refs.form.clearValidate()
            } else {
              this.$tap.alert(res.message, "warning")
            }
          })
          that.milepostList.splice(index, 1)
        })
        .catch(_ => {})
    },
    saveMilepost(index) {
      postAction(this.url.saveMilepost, { milepost: this.milepostList[index], projectcode: this.projectinfo.projectcode, planid: this.parentId }).then(res => {
        if (res.success) {
          this.$refs.form.clearValidate()
          if (res.result.operatecode) {
            this.$set(this.milepostList[index], "operatecode", res.result.operatecode)
            this.$set(this.milepostList[index], "milepostcode", res.result.milepostcode)
            this.$set(this.milepostList[index], "milepoststate", res.result.milepoststate)
            this.$set(this.milepostList[index], "id", res.result.id)
          }
        } else {
          this.$tap.alert(res.message, "warning")
        }
      })
    },
    addCompetitor() {
      this.milepostList.push({})
      this.saveMilepost(this.milepostList.length - 1)
    },
    // userConfirm(selectData) {
    //   const selectedUser = selectData[0]
    //   const { code, name } = selectedUser
    //   this.$set(this.model, "responsiblecode", code)
    //   this.$set(this.model, "responsible", name)
    //   this.$set(this.model, "projectcode", this.projectinfo.projectcode)
    // },
    loaded() {
      // 页面加载完毕执行
      if (this.isAdd) {
        this.$set(this.model, "planid", this.parentId)
      }
      this.milepostLoadInfo()
    },
    milepostLoadInfo() {
      if (this.parentId !== "") {
        getAction(this.url.milepostLoadInfo, { id: this.parentId }).then(res => {
          if (res.success) {
            this.milepostList = res.result.milepostList
          } else {
            this.$tap.alert(res.message, "warning")
          }
        })
      }
    },
    getSdProjectTeamData(selectionRow, selectKey, selectionValue) {
      this.$set(this.milepostList[this.milepostIndex], "responsiblecode", selectionRow.usercode)
      this.$set(this.milepostList[this.milepostIndex], "responsible", selectionRow.username)
      this.$set(this.milepostList[this.milepostIndex], "projectcode", this.projectinfo.projectcode)
    },
    opensdProjectTeamRefDialog(index) {
      this.milepostIndex = index
      this.externalQueryParamForPool = {
        qry_projectcode: this.projectinfo.projectcode,
        qry_state: 9,
        qry_enabled: 1,
        qry_appointmenttype: 1
      }
      this.$refs.sdProjectTeamRef.visible = true
    },
    doRefresh() {
      // this.$refs.task[task.length-1].doRefresh()
    },
    formatDateToMicro(date) {
      return new Date(formatDate(new Date(date), 'yyyy-MM-dd')).getTime()
    }
  },
  watch: {
    // 当projectInfo改变时，为externalQueryParam赋值
    projectinfo(newVal, oldVal) {
      this.externalQueryParam.qry_projectcode = newVal.projectcode
    }
  }
}
</script>
